package com.na.tools.mail;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {
	
	public void send(String fromMailAddr, String fromMailPwd, String fromMailSmtp,
			String[] toMailAddrs, String subject, String content,
			String[] attaches) throws Exception {
		Session session = getSession();
		Transport transport = session.getTransport("smtp");
		transport.connect(fromMailSmtp, fromMailAddr, fromMailPwd);
		Message message = createMessage(session, fromMailAddr, toMailAddrs, subject, content, attaches);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}
	
	private Session getSession() throws Exception {
		Properties property = new Properties();
		property.setProperty("mail.transport.protocol", "smtp");
		property.setProperty("mail.smtp.auth", "true");
		return Session.getInstance(property);
	}
	
	private Message createMessage(Session session, String fromMailAddr, String[] toMailAddrs, String subject, String content, String[] attaches) throws Exception {
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromMailAddr));
		for (String toAddr : toMailAddrs) {
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
		}
		message.setSubject(subject);
		Multipart multipart = new MimeMultipart();
		// text body
		BodyPart body = new MimeBodyPart();
		body.setText(content);
		multipart.addBodyPart(body);
		// binary body
		body = new MimeBodyPart();
		for (String attach : attaches) {
			FileDataSource ds = new FileDataSource(attach);
			body.setDataHandler(new DataHandler(ds));
			body.setFileName(ds.getName());
			multipart.addBodyPart(body);
		}
		message.setContent(multipart);
		message.saveChanges();
		return message;
	}
	
	static void printHelp() {
		PrintStream out = System.out;
		out.println("--help print the help content.");
		out.println("--from the source mail's address.");
		out.println("--password the source mail's password.");
		out.println("--smtp the source mail's smtp server.");
		out.println("--to the destination mails' address.");
		out.println("--subject the mail's subject.");
		out.println("--content the mail's content.");
		out.println("--attaches the mail's attachments.");
	}
	
	static Map<String, List<String>> parseArgs(String[] args) {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		List<String> value = null;
		for (String arg : args) {
			if (arg.startsWith("--")) {
				value = new ArrayList<String>(3);
				map.put(arg, value);
			} else {
				value.add(arg);
			}
		}
		return map;
	}
	
	static <T> void printArray(T[] array) {
		StringBuilder buf = new StringBuilder();
		for (T a : array) {
			buf.append(a).append(", ");
		}
		buf.setLength(buf.length() - 2);
		System.out.println(buf.toString());
	}

	public static void main(String[] args) {
		if (args == null || args.length == 0 || "--help".equals(args[0])) {
			printHelp();
			return;
		}
		printArray(args);
		try {
			Map<String, List<String>> argsMap = parseArgs(args);
			MailSender instance = new MailSender();
			String fromMailAddr = argsMap.get("--from").get(0);
			String fromMailPwd = argsMap.get("--password").get(0);
			String fromMailSmtp = argsMap.get("--smtp").get(0);
			String[] toMailAddrs = argsMap.get("--to").toArray(new String[0]);
			String subject = argsMap.get("--subject").get(0);
			String content = argsMap.get("--content").get(0);
			String[] attaches = argsMap.get("--attaches").toArray(new String[0]);
			instance.send(fromMailAddr, fromMailPwd, fromMailSmtp, toMailAddrs, subject, content, attaches);
			System.out.println("Mail send success.");
		} catch (Exception e) {
			System.err.println("Mail send failed...");
			e.printStackTrace();
			System.out.println();
			printHelp();
		}
	}

}
